﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Commons.Data;
using Commons.Entity;
using System.Linq.Expressions;

namespace TestHttpModules.Controllers
{
    #region 数据层

    public class EFTestBase : DbContextRepositoryBase
    {
        private static string conn;

        static EFTestBase()
        {
            if (System.Configuration.ConfigurationManager.ConnectionStrings["testEntities"] == null)
                throw new ArgumentException("请配置testEntities串");
            conn = System.Configuration.ConfigurationManager.ConnectionStrings["testEntities"].ToString();
        }
        public EFTestBase()
            : base(DbFactory.Intance(conn))
        {
            _db.Configuration.LazyLoadingEnabled = true;
        }

    }
    /// <summary>
    /// 对BLL层开放的统一操作对象
    /// </summary>
    public class Repository : EFTestBase, IRepository
    {
    }
    /// <summary>
    /// 用户个性操作对象
    /// </summary>
    public class UserRepository : EFTestBase
    {
        /// <summary>
        /// 返回类型为派生类
        /// </summary>
        /// <returns></returns>
        public IQueryable<User> GetModel()
        {
            return (from data1 in base.GetEntities<User>()
                    join data2 in base.GetEntities<User_Profile>() on data1.ID equals data2.ID into list
                    select new User_Ext
                    {
                        ID = data1.ID,
                        Name = data1.Name,
                        Status = data1.Status,
                        Password = data1.Password,
                        User_Profile = list.FirstOrDefault(),
                    });
        }
        public IQueryable<User> GetDetailModel()
        {
            //var linq = (from data1 in base.GetEntities<User>()
            //            join data2 in base.GetEntities<User_Profile>() on data1.ID equals data2.ID into list
            //            join data3 in new ProductRepository().GetModel() on data1.ID equals data3.UserID into list2
            //            select new User_Ext
            //            {
            //                ID = data1.ID,
            //                Name = data1.Name,
            //                Status = data1.Status,
            //                User_Profile = list.FirstOrDefault(),
            //                Product = list2,
            //            });
            //return linq;
            return null;
        }

        public User GetEntity(int id)
        {
            return (from data1 in base.GetEntities<User>()
                    join data2 in base.GetEntities<User_Profile>() on data1.ID equals data2.ID into list
                    select new User_Ext
                    {
                        ID = data1.ID,
                        Name = data1.Name,
                        Status = data1.Status,
                        Password = data1.Password,
                        User_Profile = list.FirstOrDefault(),
                    }).FirstOrDefault(i => i.ID == id);
        }
    }
    public class User_ProfileRepository : EFTestBase
    {

    }
    /// <summary>
    /// 产品个性操作对象
    /// </summary>
    public class ProductRepository : EFTestBase
    {
        public IQueryable<Product> GetModel()
        {
            return (from data1 in base.GetEntities<Product>()
                    join data2 in base.GetEntities<User>() on data1.ID equals data2.ID
                    select new Product_Ext
                    {
                        ID = data1.ID,
                        Name = data1.Name,
                        Status = data1.Status,
                        Price = data1.Price,
                        User = data2,
                        UserID = data1.UserID
                    });
        }
    }

    #endregion

    #region 业务层
    public abstract class BLLBase
    {
        public BLLBase()
        {
            this.VM = new VMessage();
        }
        /// <summary>
        /// 用户于BLL层进行数据访问的对象
        /// </summary>
        protected IRepository LoadRepository
        {
            get { return new Repository(); }
        }
        public VMessage VM { get; private set; }
    }
    /// <summary>
    /// 业务层－具体功能类
    /// </summary>
    public class UserManager : BLLBase
    {
        UserRepository _userRepository;
        User_ProfileRepository _user_ProfileRepository;
        public UserManager()
        {
            _userRepository = new UserRepository();
            _user_ProfileRepository = new User_ProfileRepository();
        }
        /// <summary>
        /// 得到用户
        /// </summary>
        /// <returns></returns>
        public List<User> GetUser(PredicateList<User> predicate, Action<Orderable<User>> orderby)
        {
            var linq = (from data1 in base.LoadRepository.GetEntities<User>()
                        join data2 in base.LoadRepository.GetEntities<User_Profile>() on data1.ID equals data2.ID into list
                        join data3 in new ProductRepository().GetModel() on data1.ID equals data3.UserID into list2
                        select new User_Ext
                        {
                            ID = data1.ID,
                            Name = data1.Name,
                            Status = data1.Status,
                            User_Profile = list.FirstOrDefault(),
                            Product = list2,
                        });
            var linq2 = new testEntities().User.ToList();
            return linq.LinqForPredicate<User>(predicate, orderby).ToList();

        }
        /// <summary>
        ///  添加用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public VMessage AddUser(User entity)
        {
            try
            {
                LoadRepository.Insert<User>(entity);
            }
            catch (Exception ex)
            {
                VM.AddItem(ex.Message);
                throw;
            }
            return VM;
        }
    }
    #endregion

    #region WEBUI层
    public class EFController : Controller
    {
        UserRepository userRepository;
        User_ProfileRepository user_ProfileRepository;
        UserManager _userManager;
        public EFController()
        {
            userRepository = new UserRepository();
            user_ProfileRepository = new User_ProfileRepository();
            _userManager = new UserManager();
        }
        #region 插入，编辑，删除列表
        #region 插入列表
        public ActionResult CreateList()
        {
            return View();
        }
        [HttpPost]
        public ActionResult CreateList(User entity)//当这个action的参数是一个模型时，才被触发ModelState对象
        {
            var form = Request.Form;
            if (ModelState.IsValid)
            {
                List<User> userList = new List<TestHttpModules.User>();
                string[] status = form.GetValues("Status");
                int j = 0;
                form.GetValues("Name").ToList().ForEach(i =>
                {
                    userList.Add(new User { Name = i, Status = Convert.ToInt32(status[j]) });
                    j++;
                });
                userRepository.Insert<User>(userList);
                return RedirectToAction("Index");
            }
            return View();
        }
        #endregion

        #region 编辑列表
        public ActionResult EditList()
        {
            List<User> userList = userRepository.GetEntities<User>().Take(5).ToList();
            return View(userList);
        }
        [HttpPost]
        public ActionResult EditList(FormCollection form)
        {
            if (ModelState.IsValid)
            {
                List<User> userList = new List<User>();
                string[] status = form.GetValues("Status");
                string[] id = form.GetValues("ID");
                int j = 0;
                form.GetValues("Name").ToList().ForEach(i =>
                {
                    userList.Add(new User
                    {
                        ID = Convert.ToInt32(id[j]),
                        Name = i,
                        Status = Convert.ToInt32(status[j]),
                        User_Profile = new User_Profile { ID = Convert.ToInt32(id[j]) }
                    });
                    j++;
                });
                userRepository.Update<User>(userList);
                return RedirectToAction("Index");
            }
            return View(userRepository.GetEntities<User>().Take(5).ToList());
        }

        #endregion

        #region 删除列表
        public ContentResult Delete(string id)
        {
            List<User> delList = new List<TestHttpModules.User>();
            id.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(i =>
            {
                delList.Add(new User { ID = Convert.ToInt32(i) });
            });
            try
            {
                userRepository.Delete<User>(delList);
                return Content("true");
            }
            catch (Exception)
            {
                return Content("false");
                throw;
            }

        }
        /// <summary>
        /// AJAX POST 删除方法
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeleteMore(FormCollection form)
        {
            List<User> delList = new List<TestHttpModules.User>();
            string[] ids = form.GetValues("ID");
            Array.ForEach(ids, i =>
            {
                delList.Add(new User { ID = Convert.ToInt32(i) });
            });
            try
            {
                userRepository.Delete<User>(delList);
            }
            catch (Exception)
            {
                throw;
            }
            List<User> model = userRepository.GetModel().ToList();
            return PartialView("List", model);
        }
        #endregion
        #endregion

        #region 插入，编辑，删除实体
        #region 插入实体
        public ActionResult Create(int? id)
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(User entity)
        {
            ModelState.Remove("Status");//手动移除一些异常从ModelState
            entity.Status = 200;//初始化一些值
            if (ModelState.IsValid)
            {
                try
                {
                    if (entity.User_Profile != null)
                    {
                        entity.InsertAfter += () =>
                        {
                            user_ProfileRepository.Insert<User_Profile>(new User_Profile
                            {
                                ID = entity.ID,
                                RealName = entity.User_Profile.RealName,
                            });

                        };
                    }
                    string res;
                    VMessage vm = new UserManager().AddUser(entity);
                    if (vm.IsComplete)
                        res = "操作成功";
                    else
                        res = "失败失败，信息为：" + vm.GetMessage();

                }
                catch (Exception)
                {

                    throw;
                }

                return RedirectToAction("Index");
            }
            return View();
        }


        #endregion

        #region 编辑实体
        public ActionResult Edit(int? id)
        {
            var model = userRepository.GetEntity(id.Value);
            return View(model);
        }
        [HttpPost]
        public ActionResult Edit(User entity)
        {
            if (ModelState.IsValid)//实体模型验证是否通过，如果数据表字段不允许为NULL，但如果前台为NULL，则返回值为false
            {

                entity.UpdateAfter += () =>
                {
                    if (entity.User_Profile != null)
                    {
                        if (user_ProfileRepository.GetEntity<User_Profile>(k => k.ID == entity.ID) == null)
                            user_ProfileRepository.Insert<User_Profile>(new User_Profile
                            {
                                ID = entity.ID,
                                RealName = entity.User_Profile.RealName,
                            });
                        else
                            user_ProfileRepository.Update<User_Profile>(k => new User_Profile
                            {
                                ID = entity.ID,
                                RealName = entity.User_Profile.RealName
                            });
                    }
                };
                userRepository.Update<User>(new User
                {
                    ID = entity.ID,
                    Name = entity.Name,
                });
                //  return RedirectToAction("Index");//返回到列表页
                return RedirectToAction("Edit");//自身刷新
            }
            return View();
        }
        #endregion

        #region 删除实体
        public ActionResult Del(int? id)
        {
            if (id.HasValue)
                userRepository.Delete<User>(new User { ID = id.Value });
            return RedirectToAction("Index");

        }
        #endregion

        #endregion

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string name)
        {
            PredicateList<User> predicate = new PredicateList<TestHttpModules.User>();
            if (!string.IsNullOrWhiteSpace(name))
                predicate.Add(i => i.Name.Contains(name.Trim()));
            Action<Orderable<User>> orderby;
            orderby = i => i.Asc(j => j.ID);
            List<User> model = _userManager.GetUser(predicate, orderby);
            if (Request.IsAjaxRequest())
                return PartialView("List", model);
            return View(model);
        }
    }

    #endregion
}
